"""
教学质量评估API端点
"""
import base64
import io
from datetime import datetime, timedelta
from typing import List, Dict, Any, Optional
from fastapi import APIRouter, HTTPException, UploadFile, File, Form
from fastapi.responses import JSONResponse
import numpy as np
import cv2
import logging

from backend.schemas.teaching_quality import (
    TeacherBehaviorAnalysisRequest, TeacherBehaviorAnalysisResponse,
    InteractionAnalysisRequest, InteractionAnalysisResponse,
    TeachingStyleAnalysisRequest, TeachingStyleAnalysisResponse,
    TeachingQualityReportRequest, TeachingQualityReportResponse,
    TeacherStatisticsRequest, TeacherStatisticsResponse,
    to_dict
)
from backend.services.teaching_quality_main_service import TeachingQualityService

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/teaching-quality", tags=["教学质量评估"])

# 全局服务实例
teaching_service = TeachingQualityService()


@router.post("/analyze-behavior")
async def analyze_teacher_behavior(
    classroom_id: str = Form(...),
    session_id: str = Form(...),
    teacher_detection: str = Form(...),  # JSON字符串
    image: UploadFile = File(...)
):
    """
    分析教师行为
    
    - **classroom_id**: 教室ID
    - **session_id**: 课堂会话ID
    - **teacher_detection**: 教师检测结果（JSON格式）
    - **image**: 课堂图像文件
    """
    try:
        logger.info(f"开始分析教室 {classroom_id} 会话 {session_id} 的教师行为")
        
        # 解析教师检测结果
        import json
        detection = json.loads(teacher_detection)
        
        # 读取图像数据
        image_data = await image.read()
        nparr = np.frombuffer(image_data, np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        if img is None:
            raise HTTPException(status_code=400, detail="无法解析图像数据")
        
        # 执行行为分析
        behavior_data = await teaching_service.analyze_teacher_behavior(img, detection)
        
        # 转换为响应格式
        response_data = {
            'analysis_id': f"behavior_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
            'teacher_id': behavior_data.teacher_id,
            'timestamp': behavior_data.timestamp.isoformat(),
            'behavior': behavior_data.behavior.value,
            'gesture_data': behavior_data.gesture_data,
            'facial_expression': behavior_data.facial_expression,
            'movement_data': behavior_data.movement_data,
            'voice_features': behavior_data.voice_features,
            'fatigue_level': behavior_data.fatigue_level.value,
            'confidence': behavior_data.confidence
        }
        
        logger.info(f"教师行为分析完成，教师ID: {behavior_data.teacher_id}")
        return JSONResponse(content=response_data)
        
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="教师检测结果格式错误")
    except Exception as e:
        logger.error(f"教师行为分析失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"教师行为分析失败: {str(e)}")


@router.post("/analyze-interaction")
async def analyze_interaction(
    teacher_id: str,
    classroom_id: str,
    session_id: str,
    student_attention_data: List[Dict[str, Any]],
    audio_features: Optional[Dict[str, Any]] = None
):
    """
    分析师生互动
    
    - **teacher_id**: 教师ID
    - **classroom_id**: 教室ID
    - **session_id**: 课堂会话ID
    - **student_attention_data**: 学生专注度数据
    - **audio_features**: 音频特征（可选）
    """
    try:
        logger.info(f"开始分析教师 {teacher_id} 的师生互动")
        
        # 执行互动分析
        interaction_data = await teaching_service.analyze_interaction(
            teacher_id, student_attention_data, audio_features
        )
        
        # 转换为响应格式
        response_data = {
            'interaction_id': interaction_data.interaction_id,
            'teacher_id': interaction_data.teacher_id,
            'timestamp': interaction_data.timestamp.isoformat(),
            'interaction_type': interaction_data.interaction_type,
            'duration': interaction_data.duration,
            'student_response_count': interaction_data.student_response_count,
            'teacher_question_count': interaction_data.teacher_question_count,
            'interaction_quality': interaction_data.interaction_quality.value,
            'engagement_score': interaction_data.engagement_score,
            'effectiveness_score': interaction_data.effectiveness_score
        }
        
        logger.info(f"师生互动分析完成，互动ID: {interaction_data.interaction_id}")
        return JSONResponse(content=response_data)
        
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        logger.error(f"师生互动分析失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"师生互动分析失败: {str(e)}")
@ro
uter.post("/analyze-style")
async def analyze_teaching_style(teacher_id: str, analysis_period: int = 30):
    """
    分析教学风格
    
    - **teacher_id**: 教师ID
    - **analysis_period**: 分析周期（天数）
    """
    try:
        logger.info(f"开始分析教师 {teacher_id} 的教学风格")
        
        # 执行风格分析
        style_analysis = teaching_service.analyze_teaching_style(teacher_id)
        
        # 转换为响应格式
        response_data = {
            'analysis_id': style_analysis.analysis_id,
            'teacher_id': style_analysis.teacher_id,
            'teaching_style': style_analysis.teaching_style.value,
            'style_confidence': style_analysis.style_confidence,
            'behavior_distribution': style_analysis.behavior_distribution,
            'interaction_patterns': style_analysis.interaction_patterns,
            'strengths': style_analysis.strengths,
            'improvement_areas': style_analysis.improvement_areas,
            'recommendations': style_analysis.recommendations
        }
        
        logger.info(f"教学风格分析完成，分析ID: {style_analysis.analysis_id}")
        return JSONResponse(content=response_data)
        
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        logger.error(f"教学风格分析失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"教学风格分析失败: {str(e)}")


@router.post("/generate-report")
async def generate_quality_report(
    teacher_id: str,
    classroom_id: str,
    start_time: Optional[str] = None,
    end_time: Optional[str] = None
):
    """
    生成教学质量报告
    
    - **teacher_id**: 教师ID
    - **classroom_id**: 教室ID
    - **start_time**: 开始时间（ISO格式，可选）
    - **end_time**: 结束时间（ISO格式，可选）
    """
    try:
        logger.info(f"开始生成教师 {teacher_id} 的教学质量报告")
        
        # 解析时间范围
        time_range = None
        if start_time and end_time:
            start_dt = datetime.fromisoformat(start_time.replace('Z', '+00:00'))
            end_dt = datetime.fromisoformat(end_time.replace('Z', '+00:00'))
            time_range = (start_dt, end_dt)
        
        # 生成报告
        report = teaching_service.generate_quality_report(
            teacher_id, classroom_id, time_range
        )
        
        # 转换为响应格式
        response_data = {
            'report_id': report.report_id,
            'teacher_id': report.teacher_id,
            'classroom_id': report.classroom_id,
            'analysis_period': [
                report.analysis_period[0].isoformat(),
                report.analysis_period[1].isoformat()
            ],
            'overall_score': report.overall_score,
            'behavior_analysis': report.behavior_analysis,
            'interaction_analysis': report.interaction_analysis,
            'style_analysis': {
                'teaching_style': report.style_analysis.teaching_style.value,
                'style_confidence': report.style_analysis.style_confidence,
                'strengths': report.style_analysis.strengths,
                'improvement_areas': report.style_analysis.improvement_areas,
                'recommendations': report.style_analysis.recommendations
            },
            'fatigue_analysis': report.fatigue_analysis,
            'improvement_suggestions': report.improvement_suggestions,
            'generated_at': report.generated_at.isoformat()
        }
        
        logger.info(f"教学质量报告生成完成，报告ID: {report.report_id}")
        return JSONResponse(content=response_data)
        
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        logger.error(f"生成教学质量报告失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"生成教学质量报告失败: {str(e)}")


@router.get("/teacher-statistics/{teacher_id}")
async def get_teacher_statistics(
    teacher_id: str,
    start_time: Optional[str] = None,
    end_time: Optional[str] = None
):
    """
    获取教师统计信息
    
    - **teacher_id**: 教师ID
    - **start_time**: 开始时间（ISO格式，可选）
    - **end_time**: 结束时间（ISO格式，可选）
    """
    try:
        logger.info(f"获取教师 {teacher_id} 的统计信息")
        
        # 解析时间范围
        time_range = None
        if start_time and end_time:
            start_dt = datetime.fromisoformat(start_time.replace('Z', '+00:00'))
            end_dt = datetime.fromisoformat(end_time.replace('Z', '+00:00'))
            time_range = (start_dt, end_dt)
        
        # 获取统计信息
        statistics = teaching_service.get_teacher_statistics(teacher_id, time_range)
        
        if 'error' in statistics:
            raise HTTPException(status_code=404, detail=statistics['error'])
        
        # 转换时间格式
        if statistics.get('time_range'):
            statistics['time_range'] = [
                statistics['time_range'][0].isoformat(),
                statistics['time_range'][1].isoformat()
            ]
        
        logger.info(f"教师统计信息获取完成")
        return JSONResponse(content=statistics)
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取教师统计信息失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取教师统计信息失败: {str(e)}")


@router.get("/teaching-behaviors")
async def get_teaching_behaviors():
    """获取教学行为类型列表"""
    from backend.services.teaching_quality_service import TeachingBehavior
    return [behavior.value for behavior in TeachingBehavior]


@router.get("/teaching-styles")
async def get_teaching_styles():
    """获取教学风格类型列表"""
    from backend.services.teaching_quality_service import TeachingStyle
    return [style.value for style in TeachingStyle]


@router.get("/fatigue-levels")
async def get_fatigue_levels():
    """获取疲劳度等级列表"""
    from backend.services.teaching_quality_service import FatigueLevel
    return [level.value for level in FatigueLevel]


@router.get("/interaction-qualities")
async def get_interaction_qualities():
    """获取互动质量等级列表"""
    from backend.services.teaching_quality_service import InteractionQuality
    return [quality.value for quality in InteractionQuality]


@router.get("/dashboard/{teacher_id}")
async def get_teaching_dashboard(
    teacher_id: str,
    time_range: str = "24h"  # 1h, 6h, 24h, 7d, 30d
):
    """
    获取教学仪表板数据
    
    - **teacher_id**: 教师ID
    - **time_range**: 时间范围
    """
    try:
        logger.info(f"获取教师 {teacher_id} 的仪表板数据，时间范围: {time_range}")
        
        # 计算时间范围
        end_time = datetime.now()
        time_deltas = {
            '1h': timedelta(hours=1),
            '6h': timedelta(hours=6),
            '24h': timedelta(days=1),
            '7d': timedelta(days=7),
            '30d': timedelta(days=30)
        }
        
        if time_range not in time_deltas:
            raise HTTPException(status_code=400, detail="无效的时间范围")
        
        start_time = end_time - time_deltas[time_range]
        
        # 获取教师统计
        statistics = teaching_service.get_teacher_statistics(
            teacher_id, (start_time, end_time)
        )
        
        # 构建仪表板数据
        dashboard_data = {
            'dashboard_id': f"dashboard_{teacher_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
            'teacher_id': teacher_id,
            'time_range': time_range,
            'generated_at': datetime.now().isoformat(),
            'summary_statistics': {
                'total_observations': statistics.get('total_observations', 0),
                'total_interactions': statistics.get('total_interactions', 0),
                'avg_fatigue_level': statistics.get('avg_fatigue_level', 0),
                'avg_engagement_score': statistics.get('avg_engagement_score', 0),
                'avg_effectiveness_score': statistics.get('avg_effectiveness_score', 0),
                'most_common_behavior': statistics.get('most_common_behavior', 'unknown')
            },
            'behavior_trends': {
                'behavior_distribution': statistics.get('behavior_distribution', {}),
                'fatigue_distribution': statistics.get('fatigue_distribution', {})
            },
            'alerts': [],  # 可以添加告警信息
            'recommendations': []  # 可以添加建议
        }
        
        # 添加基于数据的建议
        if statistics.get('avg_fatigue_level', 0) > 3:
            dashboard_data['recommendations'].append("注意休息，当前疲劳度较高")
        
        if statistics.get('avg_engagement_score', 0) < 60:
            dashboard_data['recommendations'].append("建议增加互动环节，提高学生参与度")
        
        logger.info(f"仪表板数据获取完成")
        return JSONResponse(content=dashboard_data)
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取仪表板数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取仪表板数据失败: {str(e)}")


@router.delete("/data/{teacher_id}")
async def clear_teacher_data(teacher_id: str):
    """
    清除教师数据
    
    - **teacher_id**: 教师ID
    """
    try:
        # 清除教师的历史数据
        if teacher_id in teaching_service.teacher_behavior_storage:
            del teaching_service.teacher_behavior_storage[teacher_id]
        
        if teacher_id in teaching_service.interaction_storage:
            del teaching_service.interaction_storage[teacher_id]
        
        # 清除相关的分析数据
        analyses_to_delete = []
        for analysis_id, analysis in teaching_service.style_analysis_storage.items():
            if analysis.teacher_id == teacher_id:
                analyses_to_delete.append(analysis_id)
        
        for analysis_id in analyses_to_delete:
            del teaching_service.style_analysis_storage[analysis_id]
        
        # 清除相关的报告数据
        reports_to_delete = []
        for report_id, report in teaching_service.quality_reports_storage.items():
            if report.teacher_id == teacher_id:
                reports_to_delete.append(report_id)
        
        for report_id in reports_to_delete:
            del teaching_service.quality_reports_storage[report_id]
        
        return {"message": f"教师 {teacher_id} 的数据已清除"}
        
    except Exception as e:
        logger.error(f"清除教师数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清除教师数据失败: {str(e)}")


@router.get("/health")
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "service": "teaching_quality",
        "timestamp": datetime.now().isoformat(),
        "data_counts": {
            "teacher_behaviors": sum(len(data) for data in teaching_service.teacher_behavior_storage.values()),
            "interactions": sum(len(data) for data in teaching_service.interaction_storage.values()),
            "style_analyses": len(teaching_service.style_analysis_storage),
            "quality_reports": len(teaching_service.quality_reports_storage)
        }
    }